import wechatpy
from django.contrib import auth
from wechatpy.enterprise.client.api import WeChatOAuth
from wechatpy.enterprise.exceptions import InvalidCorpIdException
from wechatpy import enterprise, parse_message
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
import uuid, datetime, json, time
import itkf as config
from django.utils.safestring import mark_safe
from wechatpy.enterprise.crypto import WeChatCrypto
from wechatpy.exceptions import InvalidSignatureException
import os
import urllib
import itkf
from apps.services import models
from django.core.cache import cache
from wechatpy.enterprise import WeChatClient
from wechatpy.session.redisstorage import RedisStorage
from redis import Redis
from urllib.parse import quote
from django.utils.safestring import mark_safe
import json
import urllib3

ENV_PROFILE = os.getenv("ENV")
if ENV_PROFILE == "test":
    import itkf.test_settings as config
elif ENV_PROFILE == "production":
    import itkf.prd_settings as config
else:
    import itkf.settings as config

corpid = config.weChatWork["corpid"]
sourceFile = config.weChatWork["sourceFile"]
serviceUser = config.weChatWork["serviceUser_"]
customeUser = config.weChatWork["customeUser_"]
media_image_url = config.weChatWork["media_image_url"]
avatar_image_url = config.weChatWork["avatar_image_url"]
domain = config.domain


# 群消息提问内容
def template_string(**kwargs):
    return """<font color="warning">新消息</font>
> 姓名：{username}
> UM：{um}
> 发送内容：{content}
> 点击查看:{url}
""".format(**kwargs)


# 查看请求信息

def requestInfo(request):
    result = request.environ.items()
    return render(request, 'requestInfo.html', {'rinfo': result})


# 登录功能


# 注销
def logout(request):
    kfUser = models.KF.objects.filter(userid=request.user.username).first()
    kfUser.status = False
    kfUser.save()
    auth.logout(request)
    return redirect('/admin/login/')


# 注册
def registered(request, userid):
    user = User.objects.filter(username=userid).first()
    if not user:
        user = User.objects.create_user(username=userid, email=str(userid) + "@pingan.com.cn", password=uuid.uuid1(),
                                        is_staff=True, is_active=True)
    auth.login(request, user)
    return user


# Create your tests here.
@login_required
def index(request):
    method = request.method.upper()
    agentid = request.GET.get("nid", 1)
    if method == "GET":
        return render(request, "index.html")
    elif method == "POST":
        UserId = request.user.username
        kfUser = models.KF.objects.filter(userid=UserId).first()
        kfUser.status = True
        kfUser.save()
        print(request.POST)
        Content = request.POST.get('mine[content]')
        userid = request.POST.get('mine[id]')
        FromUserName = request.POST.get('to[id]')
        cur_time = datetime.datetime.now()
        models.Message.objects.create(ToUserName=userid, AgentID=kfUser.agent, FromUserName=FromUserName,
                                      content=Content,
                                      CreateTime=cur_time, author=request.user, editor=request.user)

        from channels.layers import get_channel_layer
        channel_layer = get_channel_layer()
        from asgiref.sync import async_to_sync
        print("FromUserName============", FromUserName)

        obj = {
            "username": request.user.first_name
            , "avatar": media_image_url + str(kfUser.avatar)
            , "id": FromUserName
            , "type": "chat_message"
            , "content": Content
        }
        print("rindex===========", FromUserName[str(FromUserName).rindex("_") + 1:])
        print("customeUser + FromUserName=============", customeUser + FromUserName)
        async_to_sync(channel_layer.group_send)(customeUser + FromUserName[str(FromUserName).rindex("_") + 1:], obj)

        obj = {
            "username": request.user.first_name
            , "avatar": media_image_url + str(kfUser.avatar)
            , "id": FromUserName
            , "type": "chat_message"
            , "content": Content
        }
        currentOnlineKF = models.KF.objects.filter(agent__id=agentid, status=True).exclude(userid=UserId)
        print(currentOnlineKF.query)
        for item in currentOnlineKF:
            async_to_sync(channel_layer.group_send)(serviceUser + str(agentid) + item.userid, obj)

        result = {"code": 200, "msg": "ok"}
        return JsonResponse(result)




# @login_required
@login_required
def custome(request):
    method = request.method.upper()
    agentid = request.GET.get("nid", 1)
    if method == "GET":
        return render(request, "custome.html",
                      {"agentid": agentid,
                       "currentUser": request.user})
    else:
        UserId = request.user.username
        print(request.POST)
        Content = request.POST.get('mine[content]')
        FromUserName = request.POST.get('to[userid]')
        cur_time = datetime.datetime.now()
        models.Message.objects.create(ToUserName=UserId, AgentID=agentid, FromUserName=FromUserName,
                                      content=Content,
                                      CreateTime=cur_time, author=request.user, editor=request.user)

        currentKF = models.KF.objects.filter(agent__id=agentid, status=True).count()
        from channels.layers import get_channel_layer
        channel_layer = get_channel_layer()
        from asgiref.sync import async_to_sync
        if currentKF > 0:
            obj = {
                "username": request.user.first_name
                , "avatar": avatar_image_url + UserId + ".png"
                , "id": FromUserName
                , "type": "chat_message"
                , "content": Content
            }

            # 首次会话查询知识库直接返回信息 未完成

            currentOnlineKF = models.KF.objects.filter(agent__id=agentid, status=True).exclude(userid=UserId)
            print(currentOnlineKF)
            for item in currentOnlineKF:
                async_to_sync(channel_layer.group_send)(serviceUser + agentid + item.userid, obj)
        else:
            sid = str(FromUserName).split('_')[1]
            print("staffService===========", sid)

            staffService = models.staffService.objects.filter(id=sid).first()
            obj = {
                "username": staffService.title
                , "avatar": media_image_url + str(staffService.avatar)
                , "id": FromUserName
                , "type": "chat_message"
                , "content": staffService.notuserText
            }
            async_to_sync(channel_layer.group_send)(customeUser + FromUserName[str(FromUserName).rindex("_") + 1:], obj)

        result = {"code": 200, "msg": "ok"}
        return JsonResponse(result)


@login_required
def GetUserList(request):
    loginUser = request.user.username
    print("loginUser=================", loginUser)
    user = models.KF.objects.filter(userid=loginUser).first()
    mine = {"username": user.username, "id": user.userid, "status": "online", "sign": "客服001",
            "avatar": media_image_url + str(user.avatar)}

    ulist = models.userList.objects.filter(agent__agentid=user.agent.agentid).values("id", "username", "userid",
                                                                                     "avatar", "sign").order_by(
        "-createTime")[0:200]

    for item in ulist:
        item["avatar"] = media_image_url + item["avatar"]
        print(item["avatar"])

    friend = [{"groupname": "今天", "id": 1, "online": len(ulist), "list": list(ulist)},
              {"groupname": "前天", "id": 2, "online": 0, "list": []},
              {"groupname": "三天前", "id": 4, "online": 0, "list": []},
              {"groupname": "已回复", "id": 5, "online": 0, "list": []},
              {"groupname": "未回复", "id": 6, "online": 0, "list": []}]
    return JsonResponse({'code': 0, 'msg': "", "data": {"mine": mine, "friend": friend, "group": []}})


@login_required
def departmentServices(request):
    loginUser = request.user.username
    mine = {"username": request.user.first_name, "id": request.user.id, "status": "online", "sign": "127.0.0.1",
            "avatar": avatar_image_url + loginUser + ".png"}
    # 好友组
    friend = []
    agent = models.agent.objects.order_by("agentid")
    for item in agent:
        # 好友列表
        ulist = []
        staff = models.staffService.objects.filter(agent__agentid=item.agentid)
        for s in staff:
            ulist.append(
                {"id": serviceUser + str(s.id) + "_" + loginUser, "username": s.title,
                 "userid": serviceUser + str(s.id) + "_" + loginUser,
                 "avatar": media_image_url + str(s.avatar), "sign": s.desc})

        friend.append({"groupname": item.name, "id": item.id, "online": len(ulist), "list": list(ulist)})

    print("friend=============", friend)
    return JsonResponse({'code': 0, 'msg': "", "data": {"mine": mine, "friend": friend, "group": []}})


@login_required
def uploadImage(request):
    file = request.FILES.get("file")

    # 2.创建一个文件(用于保存图片)
    fileName = str(uuid.uuid4()) + ".png"
    save_path = config.MEDIA_ROOT + "/" + fileName  # pic.name 上传文件的源文件名
    with open(save_path, 'wb') as f:
        # 3.获取上传文件的内容并写到创建的文件中
        for content in file.chunks():  # pic.chunks() 上传文件的内容。
            f.write(content)

    return JsonResponse(
        {'code': 0, 'msg': "", "data": {"src": "{}/itkfstatic/uploadImage/{}".format(domain, fileName)}})


@login_required
def getWelcomeText(request):
    data = request.POST.get("data", None)
    name = request.POST["data[name]"]
    type = request.POST["data[type]"]
    avatar = request.POST["data[avatar]"]
    id = request.POST["data[id]"]

    # 当前服务id
    nid = id[str(id).find("_") + 1]

    import datetime
    # 获取当前时间
    now = datetime.datetime.now()
    # 获取今天零点
    zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                         microseconds=now.microsecond)
    # 获取23:59:59
    lastToday = zeroToday + datetime.timedelta(hours=23, minutes=59, seconds=59)

    seconds = int((lastToday - now).total_seconds())
    redisKey = request.user.username + "$" + nid
    if not cache.get(redisKey):
        cache.set(redisKey, nid, timeout=seconds)

        staff = models.staffService.objects.filter(id=id[str(id).find("_") + 1]).first()

        from channels.layers import get_channel_layer
        channel_layer = get_channel_layer()
        from asgiref.sync import async_to_sync

        obj = {
            "username": name
            , "avatar": avatar
            , "id": id
            , "type": "chat_message"
            , "content": staff.welcomeText
        }

        print("rindex===========", id[str(id).rindex("_") + 1:])

        async_to_sync(channel_layer.group_send)(customeUser + id[str(id).rindex("_") + 1:], obj)

    return JsonResponse({'code': 0, 'msg': ""})


@login_required
def updateUserStatus(request):
    print(request.POST["state"])
    flag = False
    if request.POST["state"] == "online":
        flag = True

    models.KF.objects.filter(userid=request.user.username).update(status=flag)
    return JsonResponse({'code': 0, 'msg': ""})


# 微信企业号 接收消息服务器配置
from django.views.decorators.csrf import csrf_exempt


def downloadFile(data, fileType):
    '''
        result = client.media.get_url(data["MediaId"])
    file = str(uuid.uuid1()) + "." + fileType
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sourceUrl = os.path.join(BASE_DIR, sourceFile)
    LocalPath = os.path.join(sourceUrl, file)
    # os.path.join将多个路径组合后返回
    urllib.request.urlretrieve(result, LocalPath)
    return "/{0}/{1}".format(sourceFile, file)

    '''
    return "OK"


class switch_wechat_messages(object):

    def case_to_function(self, case):
        fun_name = str(case) + "Message"
        method = getattr(self, fun_name, self.unknownMessage)
        return method

    def textMessage(self, data):
        Content = data["Content"]

    def imageMessage(self, data):
        PicUrl = data["PicUrl"]

        print(data)

    def shortVideoMessage(self, data):
        print(data)

    def videoMessage(self, data):
        fileType = "avi"
        print(data)

    def voiceMessage(self, data):
        fileType = data["Format"]

        print(data)

    def locationMessage(self, data):
        print(data)

    def linkMessage(self, data):
        print(data)

    def eventMessage(self, data):
        AgentID = data["AgentID"]
        FromUserName = data["FromUserName"]
        createUser(FromUserName, AgentID)

    def unknownMessage(self, data):
        print(data)


def createUser(userid, AgentID):
    return "OK"